package top.healthylife.gateway.platform.softwind.api.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.basics.utils.utils.SystemThreadLocal;
import top.healthylife.gateway.core.util.SystemConfigUtils;
import top.healthylife.gateway.platform.softwind.api.config.SystemConfig;
import top.healthylife.gateway.platform.softwind.dto.basedto.req.SoftWindUnifyReqDto;
import top.heathylife.gateway.common.cons.SystemCons;
import top.heathylife.gateway.common.po.RecordRequestInfo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


/**
 * @author : GaoZeXi
 * @date 2021/7/20 17:57
 */
@Slf4j
public class WindHttpUtil {

    static final String SUCCESS = "200";
    static final String DATA = "data";
    static final String DOMAIN = "https://api.wfq2020.com";
    static Map<String, String> responseCode = new HashMap<>();

    static {
        responseCode.put("33", "参数错误,检查传入参数");
        responseCode.put("200", "请求成功,");
        responseCode.put("403", "无权限,请联系客服人员");
        responseCode.put("778", "数据已存在,请联系客服人员");
        responseCode.put("999", "系统异常,请联系客服人员");
        responseCode.put("11002", "渠道没有该公司授权数据,请联系客服人员");
        responseCode.put("30118", "渠道没有该公司,请联系客服人员");
        responseCode.put("30119", "渠道没有账户,请联系客服人员");
        responseCode.put("30120", "渠道账户没有配置,请联系客服人员");
        responseCode.put("30122", "您当前余额不足，请及时联系客服人员充值");
        responseCode.put("30123", "未及时结算,请联系客服人员结算");
        responseCode.put("30124", "该渠道账户被禁用,请联系客服人员");
        responseCode.put("30126", "渠道账户没有配置对应权限,请联系客服人员");
        responseCode.put("30127", "未及时续费,请联系客服人员续费");
        responseCode.put("30129", "企业数据正在处理中,请稍后");
        responseCode.put("30130", "企业税局账户信息更改,请重新授权后获取数据");
        responseCode.put("30131", "数据流程中断,需企业登录税局短信验证后,重新授权获取数据");
        responseCode.put("50111", "纳税人识别号输入错误,无法校验，请检查后提交！");
        responseCode.put("50118", "请配制渠道API参数,请配制渠道API参数");
        responseCode.put("70106", "渠道账户余额不足,请登录商户后台检查渠道余额");
        responseCode.put("100100", "渠道API调用IP白名单限制,请查看商户后台IP白名单设置情况");
        responseCode.put("100101", "签名密钥OrgKey错误,检查API接口加密参数secretKey生成方式");
        responseCode.put("100103", "API接口(V1.0)没有权限或已停用,请联系技术支持人员");
        responseCode.put("100104", "缺少企业纳税识别号参数,检查API接口企业纳税识别号参数的传参情况");
        responseCode.put("100105", "渠道已经被禁用,请联系客服！");
        responseCode.put("100106", "渠道未获取此批次数据,检查API接口企业纳税识别号及批次号传参情况");
        responseCode.put("800100", "数据缓存已被清理,请重新授权！");
    }


    public static <T> T httpRequest(SoftWindUnifyReqDto windUnifyReqDto, String url, Class<T> clazz) {
        //1.获取账号信息
        SystemConfig systemConfig = systemConfigInfo();
        try {
            systemConfig.setSecretKey(URLEncoder.encode(systemConfig.getSecretKey(),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException("SecretKey编码异常");
        }
        log.info("请求参数为:{}", JSONObject.toJSONString(windUnifyReqDto));
        log.info("账号信息为:{}", JSONObject.toJSONString(systemConfig));
        Map<String, Object> businessMap = BeanUtil.beanToMap(windUnifyReqDto);
        Map<String, Object> accountMap = BeanUtil.beanToMap(systemConfig);
        //移除授权码
        accountMap.remove("webAuthorizeChannelCode");
        businessMap.putAll(accountMap);
        String params = handleParam(businessMap);
        try {
            String finalQuestAddress = DOMAIN + url + params;
            log.info("最终请求地址:{}", finalQuestAddress);
            RecordRequestInfo.recordRequest(finalQuestAddress, null, null, "get");
            String body = HttpUtil.createGet(finalQuestAddress).execute().body();
            //将三方元数据存储到线程变量
            SystemThreadLocal.set(SystemCons.ORIGIN_DATA,body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            String code = jsonObject.getString("code");
            if (SUCCESS.equals(code)) {
                JSONObject data = jsonObject.getJSONObject(DATA);
                return data.toJavaObject(clazz);
            } else {
                if (responseCode.containsKey(code)) {
                    throw new BusinessException(responseCode.get(code));
                }
                throw new BusinessException("未知响应码:{}", code);
            }
        } catch (Exception e) {
            throw new BusinessException("微风企接口数据响应异常,异常信息:{}", e.getMessage());
        }

    }


    /**
     * 访问日志输出和配置获取
     *
     * @return 账号信息
     */
    public static SystemConfig systemConfigInfo() {
        //可直接通过工具类获取这个对象
        return (SystemConfig) SystemConfigUtils.get();
    }

    public static String handleParam(Map<String, Object> paramsMap) {
        StringBuilder stringBuilder = new StringBuilder().append("?");
        paramsMap.forEach((k, v) -> {
            if (ObjectUtil.isNotEmpty(v)) {
                stringBuilder.append(k).append("=").append(v).append("&");
            }
        });
        String str = stringBuilder.toString();
        //移除最后一个&
        return str.substring(0, str.length() - 1);
    }
}
